/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreacionRoles.java
 *
 * Created on 02/10/2011, 12:39:49 AM
 */

package GUI.AdministracionUsuarios;

import BE.Perfil;
import BE.Permisos;
import BL.PerfilBl;
import GUI.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author CarLita
 */
public class MantPerfiles extends javax.swing.JPanel {
    List<Perfil> perfiles;
    List<Permisos> permisos;
    Principal ventanaPrincipal;
    /** Creates new form CreacionRoles */
    public MantPerfiles() {
        initComponents();
    }

    public MantPerfiles(Principal ventanaPrincipal) {
        initComponents();
        this.ventanaPrincipal = ventanaPrincipal;
        buscarPerfiles();
        bloquearPorPermisos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPerfiles = new javax.swing.JTable();
        btnLimpiar = new javax.swing.JButton();
        btnCancelar3 = new javax.swing.JButton();
        btnAgregar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnRefrescar = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tblPerfiles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {
                "Id", "Nombre", 
                "Proyecto", "Marco",
                "Papel de Trabajo",
                "Hallazgo","Usuario"                
            }
        ));
        tblPerfiles.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblPerfilesMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblPerfiles);

        btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/limpiar.png"))); // NOI18N
        btnLimpiar.setText("Limpiar");

        btnCancelar3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/cancelar.png"))); // NOI18N
        btnCancelar3.setText("Cancelar");
        btnCancelar3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelar3ActionPerformed(evt);
            }
        });

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionUsuarios/new user.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/edit.gif"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/AdministracionPlantillas/minus white.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnRefrescar.setText("Refrescar");
        ocultarIdTabla();
        btnRefrescar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefrescarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(219, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnEliminar)
                                .addComponent(btnRefrescar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(110, 110, 110)
                        .addComponent(btnCancelar3, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(185, 185, 185))))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 652, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(122, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEditar)
                        .addGap(11, 11, 11)
                        .addComponent(btnEliminar)
                        .addGap(11, 11, 11)
                        .addComponent(btnRefrescar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnLimpiar)
                    .addComponent(btnCancelar3))
                .addContainerGap())
        );

        jLabel9.setFont(new java.awt.Font("Verdana", 0, 24));
        jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/imagenes/user.png"))); // NOI18N
        jLabel9.setText("Perfiles");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel9)
                .addContainerGap(685, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel9)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void btnRefrescarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefrescarActionPerformed
    buscarPerfiles();
}//GEN-LAST:event_btnRefrescarActionPerformed

private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
    eliminar();
}//GEN-LAST:event_btnEliminarActionPerformed

private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
    editar();
}//GEN-LAST:event_btnEditarActionPerformed

private void btnCancelar3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelar3ActionPerformed
    mostrarMenuOpciones();
}//GEN-LAST:event_btnCancelar3ActionPerformed

private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
    agregar();
}//GEN-LAST:event_btnAgregarActionPerformed

private void tblPerfilesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblPerfilesMousePressed
    if (evt.getClickCount()>1){
      lecturaPerfil();
    }
}//GEN-LAST:event_tblPerfilesMousePressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar3;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnRefrescar;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblPerfiles;
    // End of variables declaration//GEN-END:variables

    public void buscarPerfiles(){
        //busco perfiles
        perfiles = new PerfilBl().buscarPerfiles();
        permisos = new ArrayList<Permisos>();
        Permisos pAux;
        for (Perfil p: perfiles){//creo permisos
            pAux = UtilUsuarios.obtenerPermisos(p.getIdPerfil());
            permisos.add(pAux);
        }        
        llenarTabla();
    }
    
    private void llenarTabla(){
        Vector<String> tableHeaders = new Vector<String>();
        Vector tableData = new Vector();
        tableHeaders.add("Id");
        tableHeaders.add("Nombre");
        tableHeaders.add("Proyecto");
        tableHeaders.add("Marco");
        tableHeaders.add("Papel de Trabajo");
        tableHeaders.add("Hallazgo");
        tableHeaders.add("Usuario");
        String sAux;
        int i = 0;
        for(Perfil p : perfiles) {            
            Vector<Object> fila = new Vector<Object>();
            fila.add(p.getIdPerfil());
            fila.add(p.getNombre());
            sAux = permisos.get(i).getPermisoProyecto()==null? "-" :getPrivilegioMaximo(permisos.get(i).getPermisoProyecto(),1);
            fila.add(sAux);
            sAux = permisos.get(i).getPermisoMarco()==null? "-" :getPrivilegioMaximo(permisos.get(i).getPermisoMarco(),0);
            fila.add(sAux);
            sAux = permisos.get(i).getPermisoPapel()==null? "-" :getPrivilegioMaximo(permisos.get(i).getPermisoPapel(),2);
            fila.add(sAux);
            sAux = permisos.get(i).getPermisoHallazgo()==null? "-" :getPrivilegioMaximo(permisos.get(i).getPermisoHallazgo(),0);
            fila.add(sAux);
            sAux = permisos.get(i).getPermisoUsuario()==null? "-" :getPrivilegioMaximo(permisos.get(i).getPermisoUsuario(),0);
            fila.add(sAux);            
            tableData.add(fila);
            i++;
        }

        tblPerfiles.setModel(new DefaultTableModel(tableData, tableHeaders));
        ocultarIdTabla();
    }
    
    private String getPrivilegioMaximo(String permisos, int tipo){
        if (tipo == 1 && permisos.indexOf(UtilUsuarios.GENERAR_INFORME)>-1) return "Generar informe final";
        if (tipo == 1 && permisos.indexOf(UtilUsuarios.COMPLETAR)>-1) return "Cerrar proyecto";
        if (permisos.indexOf(UtilUsuarios.CREAR)>-1) return "Crear";
        if (permisos.indexOf(UtilUsuarios.EDITAR)>-1) return "Editar";
        if (permisos.indexOf(UtilUsuarios.VER)>-1) return "Ver";
        return "-";
    }
    
    private void ocultarIdTabla(){        
        tblPerfiles.getColumn("Id").setWidth(0);
        tblPerfiles.getColumn("Id").setMinWidth(0);
        tblPerfiles.getColumn("Id").setMaxWidth(0);
    }
    
    private void eliminar(){
        if (tblPerfiles.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(this, "Seleccione un perfil para eliminar", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int idPerfil = Integer.parseInt(tblPerfiles.getValueAt(tblPerfiles.getSelectedRow(), 0).toString());
        int opcion = JOptionPane.showConfirmDialog(this, "Está seguro que desea borrar este perfil?", "Confirmación", JOptionPane.ERROR_MESSAGE);
        if (opcion == JOptionPane.YES_OPTION){
            boolean borrado = new PerfilBl().eliminar(idPerfil);
            if (borrado){
                JOptionPane.showMessageDialog(this, "El perfil seleccionado ha sido eliminado", "Confirmacion", JOptionPane.INFORMATION_MESSAGE);
                buscarPerfiles();
            }
            else JOptionPane.showMessageDialog(this, "Ha ocurrido un error en la eliminación.\nPor favor, intente nuevamente.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void editar() {       
        int fila = tblPerfiles.getSelectedRow();
        if (fila==-1){
            JOptionPane.showMessageDialog(this, "Seleccione el marco de referencia a editar", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        int idPerfil = Integer.parseInt(tblPerfiles.getValueAt(tblPerfiles.getSelectedRow(), 0).toString());
        Perfil perfil = new PerfilBl().buscarPorId(idPerfil);
        ventanaPrincipal.panelUsuarios.mantPerfiles.setVisible(false);
        ventanaPrincipal.panelUsuarios.add(ventanaPrincipal.panelUsuarios.creacionPerfiles);    
        ventanaPrincipal.panelUsuarios.creacionPerfiles = new CreacionPerfiles(perfil, Principal.MODO_EDICION, permisos.get(fila));          
        ventanaPrincipal.panelUsuarios.creacionPerfiles.setVentanaPrincipal(ventanaPrincipal);
        ventanaPrincipal.panelUsuarios.creacionPerfiles.setVisible(true);                
        
    }
    
    private void mostrarMenuOpciones(){        
        ventanaPrincipal.panelUsuarios.add(ventanaPrincipal.panelUsuarios.menuOpciones);
        ventanaPrincipal.panelUsuarios.menuOpciones.setVisible(true);        
        ventanaPrincipal.panelUsuarios.remove(this);
    }
    
    private void agregar(){
        this.setVisible(false);
        ventanaPrincipal.panelUsuarios.mantPerfiles.setVisible(false);
        ventanaPrincipal.panelUsuarios.add(ventanaPrincipal.panelUsuarios.creacionPerfiles);
        ventanaPrincipal.panelUsuarios.creacionPerfiles = new CreacionPerfiles(ventanaPrincipal);        
        ventanaPrincipal.panelUsuarios.creacionUsuarios.setVisible(true);
    }

    private void bloquearPorPermisos() {        
        //crear y eliminar
        if (ventanaPrincipal.getPermisos().getPermisoPerfil().indexOf(UtilUsuarios.VER)>-1){            
            btnAgregar.setVisible(false);
            btnAgregar.setEnabled(false);
            btnEliminar.setVisible(false);
            btnEliminar.setEnabled(false);
            btnEditar.setVisible(false);
            btnEditar.setEnabled(false);
        }        
        if (ventanaPrincipal.getPermisos().getPermisoPerfil().indexOf(UtilUsuarios.CREAR)>-1){            
            btnAgregar.setVisible(true);
            btnAgregar.setEnabled(true);
            btnEliminar.setVisible(true);
            btnEliminar.setEnabled(true);
            btnEditar.setVisible(false);
            btnEditar.setEnabled(false);
        }        
        if (ventanaPrincipal.getPermisos().getPermisoPerfil().indexOf(UtilUsuarios.EDITAR)>-1){            
            btnAgregar.setVisible(true);
            btnAgregar.setEnabled(true);
            btnEliminar.setVisible(true);
            btnEliminar.setEnabled(true);
            btnEditar.setVisible(true);
            btnEditar.setEnabled(true);
        }        
        
    }

    private void lecturaPerfil() {
        int idPerfil = Integer.parseInt(tblPerfiles.getValueAt(tblPerfiles.getSelectedRow(), 0).toString());
        Perfil perfil = new PerfilBl().buscarPorId(idPerfil);
        ventanaPrincipal.panelUsuarios.mantPerfiles.setVisible(false);
        ventanaPrincipal.panelUsuarios.add(ventanaPrincipal.panelUsuarios.creacionPerfiles);    
        ventanaPrincipal.panelUsuarios.creacionPerfiles = new CreacionPerfiles(perfil, Principal.MODO_LECTURA, permisos.get(tblPerfiles.getSelectedRow()));          
        ventanaPrincipal.panelUsuarios.creacionPerfiles.setVentanaPrincipal(ventanaPrincipal);
        ventanaPrincipal.panelUsuarios.creacionPerfiles.setVisible(true);  
    }
}
